/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.rainbowsheep.reisorg.rest.service.controller.exception;

import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.messaging.support.ErrorMessage;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

/**
 *
 * @author ieme
 */
@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(UsernameExistsException.class)
    public @ResponseBody
    ResponseEntity<String> handleUsernameExistsException(UsernameExistsException ex) {
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<String>(ex.getMessage(), headers, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public @ResponseBody
    ResponseEntity<String> handleGenericException(Exception exception) {
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<String>("{\"reason\": \"I'm not crazy, I'm a burrito\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(EntityNotFoundException.class)
    public @ResponseBody
    ResponseEntity<String> handleNotFoundException(EntityNotFoundException ex) {
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<String>(ex.getMessage(), headers, HttpStatus.OK);
    }

    @ExceptionHandler(ForbiddenException.class)
    public @ResponseBody
    ResponseEntity<String> handleForbiddenException(ForbiddenException ex) {
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<String>(ex.getMessage(), headers, HttpStatus.FORBIDDEN);
    }

    @ExceptionHandler(PageNotFoundException.class)
    public @ResponseBody
    ResponseEntity<String> handlePageNotFoundException(PageNotFoundException ex) {
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<String>(ex.getMessage(), headers, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public @ResponseBody
    ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
        List<String> errors = new ArrayList<String>(fieldErrors.size() + globalErrors.size());
        String error;
        for (FieldError fieldError : fieldErrors) {
            error = fieldError.getField() + ", " + fieldError.getDefaultMessage();
            errors.add(error);
        }
        for (ObjectError objectError : globalErrors) {
            error = objectError.getObjectName() + ", " + objectError.getDefaultMessage();
            errors.add(error);
        }
        ErrorMessage errorMessage = new ErrorMessage((Throwable) errors);
        return new ResponseEntity(errorMessage, headers, status);
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public @ResponseBody
    ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String unsupported = "Unsupported content type: " + ex.getContentType();
        String supported = "Supported content types: " + MediaType.toString(ex.getSupportedMediaTypes());
        List<String> errors = new ArrayList<String>();
        errors.add(unsupported);
        errors.add(supported);
        ErrorMessage errorMessage = new ErrorMessage((Throwable) errors);
        return new ResponseEntity(errorMessage, headers, status);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public @ResponseBody
    ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Throwable mostSpecificCause = ex.getMostSpecificCause();
        List<String> errors = new ArrayList<String>();
        if (mostSpecificCause != null) {
            String exceptionName = mostSpecificCause.getClass().getName();
            String message = mostSpecificCause.getMessage();
            errors.add(exceptionName);
            errors.add(message);
            ErrorMessage errorMessage = new ErrorMessage((Throwable) errors);
            return new ResponseEntity(errorMessage, headers, status);
        } else {
            return new ResponseEntity(ex.getMessage(), headers, status);
        }
    }

    @ExceptionHandler(NoSuchRequestHandlingMethodException.class)
    public @ResponseBody
    ResponseEntity<Object> handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
            HttpHeaders headers,
            HttpStatus status,
            WebRequest request) {
        return new ResponseEntity(ex.getMessage(), headers, status);
    }
    
}
